import React, { Component, useContext, useState, useEffect, useRef  } from 'react';
import {Route, Switch, withRouter, NavLink} from 'react-router-dom'
import {Container} from './style'
import { DatePicker, Space, Table, Input, Button, Popconfirm, Form, Select} from 'antd';
// import CheckContent from '../CheckContent'

// 格式化时间
import moment from 'moment';
// iconfont
import '../../assets/icon/iconfont.css'
// antd样式
import 'antd/dist/antd.css';
// 事件组件
const { RangePicker } = DatePicker;

// 盘点组件

// 表格需要
const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
// 表格需要
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef();
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
  
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
  
    const save = async (e) => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
  
    let childNode = children;
  
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
  
    return <td {...restProps}>{childNode}</td>;
  };
// 表格需要
  const EditableContext = React.createContext();


// 表单
const { Option } = Select;
const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};

// import connect from './connect'
// @connect
@withRouter
class index extends Component {
    constructor(props) {
        super(props);
        this.columns = [
          {
            title: '序号',
            dataIndex: 'SN',
            width: '10%',
            editable: true,
          },
          {
            title: '制单时间',
            dataIndex: 'Time',
          },
          {
            title: '盘点单号',
            dataIndex: 'orderID',
          },
          {
            title: '盘点物品数量',
            dataIndex: 'count',
          },
          {
            title: '制单人',
            dataIndex: 'principal',
          },
          {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record) =>
              this.state.dataSource.length >= 1 ? (
                  <div>
                    {/* 盘点按钮 */}
                    <span onClick={() => this.handleCheck(record.SN)}>
                    <span>盘点 </span>
                    </span> 


                    {/* 修改按钮 */}
                    <span onClick={() => this.handleUpdata(record.SN)}>
                    <span>修改 </span>
                    </span> 


                    {/* 删除按钮 */}
                    <Popconfirm title="确认删除当前数据?" onConfirm={() => this.handleDelete(record.SN)}>
                    <span>删除</span>
                    </Popconfirm>
                    

                  </div>
              ) : null,
          },
        ];
      }
    // 数据源
    state = {
        dataSource: [
          {
            SN: 1,
            Time: '2020-11-11',
            orderID: 'PD20201111001',
            count: '200/400',
            principal:"张三"
          },
          {
            SN: 2,
            Time: '2020-11-11',
            orderID: 'PD20201111001',
            count: '200/400',
            principal:"李四"
          },
          
        ],
        count: 2,
        addShow:"none",
        updataShow:"none",
        SN:null
      };
    // 渲染
    render() {
        console.log(this.state.dataSource)
        // 表格
        const { dataSource } = this.state;
        const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
        };
        const columns = this.columns.map((col) => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: (record) => ({
            record,
            editable: col.editable,
            dataIndex: col.dataIndex,
            title: col.title,
            handleSave: this.handleSave,
            }),
        };
        });
        // 渲染区
        return (
            <Container>
                
                {/* 内容区域*/}
                <div className="main">
                    {/* 操作行 */}
                    <div className='btns'>
                        {/* 添加按钮 */}
                        <Button
                        className='addBtn'
                        onClick={this.handleAdd}
                        type="primary"
                        style={{
                            height:"36px",
                            display:"inline-block",
                            width: "80px",
                            backgroundColor: "rgba(28,144,243,1)",
                            color: "#fff",
                            textAlign: "center",
                            fontWeight: 700,
                            fontSize: "14px",
                            lineHeight: "36px",
                            borderRadius: "3px",
                            padding: 0

                        }}
                        >
                            <i className='iconfont icon-jiahao'></i>
                            <span>盘点单</span>
                        </Button>
                        {/* 时间组件 */}
                        <Space
                            direction="vertical" 
                            style={{
                                display:"inline-block",
                                marginLeft:'480px',
                                width:"245px",
                                height:"36px",
                                marginRight:'10px'
                            }}
                        >
                            <RangePicker
                            
                                defaultValue={[moment('2015/01/01', "YYYY-MM-DD"), moment('2015/01/01', "YYYY-MM-DD")]}
                            />
                        </Space> 
                        {/* 单号输入框 */}
                        <input className='orderId' type="text" placeholder="盘点单号" />
                        {/* 查询按钮 */}
                        <div className='selBtn'>
                            查询
                        </div>
                    </div>

                    {/* 表格区域 */}
                    <Table
                    components={components}
                    rowClassName={() => 'editable-row'}
                    bordered
                    dataSource={this.state.dataSource}
                    columns={columns}
                    />


                    
                    {/* 添加盘点单 */}
                    <div className="newOrder" style={{display:this.state.addShow}}>
                        <p className='newOrderTitle'>添加盘点单</p>
                        <Form {...layout} ref={this.addFormRef} name="control-ref" onFinish={this.onFinish}
                        labelAlign="left"
                        style={{padding:"0 20px"}}
                        >
                            {/* 盘点单号 */}
                            <Form.Item
                            name="orderID"
                            label="盘点单号"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input />
                            </Form.Item>
                            {/* 仓库选择 */}
                            <Form.Item
                                name="wareHouse"
                                label="盘点仓库"
                                rules={[
                                    {
                                    required: true,
                                    },
                                ]}
                                >
                                <Select
                                    placeholder="请选择仓库"
                                    allowClear
                                >
                                    <Option value="本部-综合楼1号仓库">本部-综合楼1号仓库</Option>
                                    <Option value="本部-综合楼2号仓库">本部-综合楼2号仓库</Option>
                                    <Option value="本部初中-教学楼办公用品仓库">本部初中-教学楼办公用品仓库</Option>
                                </Select>
                                </Form.Item>
                            {/* 制单人 */}
                            <Form.Item
                            name="principal"
                            label="制单人"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input />
                            </Form.Item>
                            {/* 数量 */}
                            <Form.Item
                            name="count"
                            label="数量"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input />
                            </Form.Item>
                            {/* 制单日期 */}
                            <Form.Item
                            name="time"
                            label="制单日期"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input placeholder={moment(Date.now()).format('YYYY-MM-DD')}/>
                            </Form.Item>
                            {/* 提交 取消 按钮 */}
                            <Form.Item {...tailLayout}>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                            <Button htmlType="button" onClick={this.onCancel}>
                                取消
                            </Button>
                            </Form.Item>
                        </Form>
                    </div>
                    {/* 修改盘点单 */}
                    <div className="newOrder" style={{display:this.state.updataShow}}>
                        <p className='newOrderTitle'>修改盘点单</p>

                        <Form {...layout} 
                          ref={this.addFormRef} name="control-ref" 
                          onFinish={this.onFinish}
                          labelAlign="left"
                          style={{padding:"0 20px"}}
                        >
                            {/* 盘点单号 */}
                            <Form.Item
                            name="orderID"
                            label="盘点单号"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input />
                            </Form.Item>
                            {/* 仓库选择 */}
                            <Form.Item
                                name="wareHouse"
                                label="盘点仓库"
                                rules={[
                                    {
                                    required: true,
                                    },
                                ]}
                                >
                                <Select
                                    placeholder="请选择仓库"
                                    allowClear
                                >
                                    <Option value="本部-综合楼1号仓库">本部-综合楼1号仓库</Option>
                                    <Option value="本部-综合楼2号仓库">本部-综合楼2号仓库</Option>
                                    <Option value="本部初中-教学楼办公用品仓库">本部初中-教学楼办公用品仓库</Option>
                                </Select>
                                </Form.Item>
                            {/* 制单人 */}
                            <Form.Item
                            name="principal"
                            label="制单人"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input />
                            </Form.Item>
                            {/* 数量 */}
                            <Form.Item
                            name="count"
                            label="数量"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input />
                            </Form.Item>
                            {/* 制单日期 */}
                            <Form.Item
                            name="time"
                            label="制单日期"
                            rules={[
                                {
                                required: true,
                                },
                            ]}
                            >
                            <Input placeholder={moment(Date.now()).format('YYYY-MM-DD')}/>
                            </Form.Item>
                            {/* 提交 取消 按钮 */}
                            <Form.Item {...tailLayout}>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                            <Button htmlType="button" onClick={this.onCancel}>
                                取消
                            </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>



            </Container>

            

        );
    }


    // 盘点按钮
    handleCheck =(SN)=>{
        this.props.history.push("/management/check/detail")
    }
    // 修改按钮
    handleUpdata =(SN)=>{
        this.setState({
            updataShow:"block",
            SN
        });
    }
    // 删除按钮
    handleDelete = (SN) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
        dataSource: dataSource.filter((item) => item.SN !== SN),
       
    });
    };

    // 表单
    addFormRef = React.createRef();
    onFinish = (values) => {
        const SN = this.state.SN
        console.log(!SN)
        if(!SN){
            const { count, dataSource } = this.state;
            const newData = {
                SN: count+1,
                Time: values.time,
                orderID: values.orderID,
                count:`${values.count}/800`,
                principal:values.principal
            };
            this.setState({
                dataSource: [...dataSource, newData],
                count: count + 1,
                addShow:"none",
                updataShow:'none'
            });

        }else{
            const updata = {
                SN: SN,
                Time: values.time,
                orderID: values.orderID,
                count:`${values.count}/800`,
                principal:values.principal
            }
            const index =SN-1
            this.state.dataSource.splice(index,1,updata)
            this.setState({
                dataSource:this.state.dataSource,
                addShow:"none",
                updataShow:'none'
            })
            
        }

    };

    // 添加盘点单
    handleAdd = () => {
        this.setState({
            addShow:"block"
        });
    };
    // 弹窗内取消按钮
    onCancel = () => {
        this.addFormRef.current.resetFields();
        this.setState({
            addShow:"none",
            updataShow:"none"
        });
    };

}

export default index;

